﻿using System;
using Resources;
using Wicresoft.RDW.Presentation;
using System.IO;
using System.Web;


namespace Wicresoft.RDW.LocationDocument
{
    public partial class Update : BasePage_BackEnd
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitData();
                
            }
        }

        protected void InitData()
        {
            txtNameCN.Text = string.Empty;
            txtNameEN.Text = string.Empty;
            ddlLocation.DataSource = LocationPresent.GetList();
            ddlLocation.DataTextField = "Name_CN";
            ddlLocation.DataValueField = "LocationId";
            ddlLocation.DataBind();
            if (string.Equals(GetQueryString("pageStatus"), "edit", StringComparison.CurrentCultureIgnoreCase))
            {
                int locationDocumentId = Id;
                var locatonDocument = LocationDocumentPresent.GetById(locationDocumentId);
                if (locatonDocument != null)
                {
                    txtNameCN.Text = locatonDocument.Name_CN;
                    txtNameEN.Text = locatonDocument.Name_EN;
                    ddlLocation.SelectedValue = locatonDocument.LocationId.ToString();
                }
                PageStatus = Utility.PageStatus.Edit;
            }
            else if (string.Equals(GetQueryString("pageStatus"), "new", StringComparison.CurrentCultureIgnoreCase))
            {
                PageStatus = Utility.PageStatus.New;
            }
            //else { this.phMain.Visible = false; }
        }

        public override void InitControlResource()
        {
            btnSubmit.Text = ManageResource.mgr_btnOK;
            btnCancelClose.Text = ManageResource.mgr_btnCancel;
            rfvtxtNameCN.ErrorMessage = ManageResource.LocationDocument_NameCNNull;
            rfvtxtNameEN.ErrorMessage = ManageResource.LocationDocument_NameENNull;
            lblUploadError.Text = string.Empty;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string path = string.Empty;
            switch (PageStatus)
            {
                case Utility.PageStatus.Edit:
                    if (!uploadDocument("edit", Id, out path))
                        return;
                    var locationDocument = LocationDocumentPresent.GetById(Id);
                    if (locationDocument != null)
                    {
                        if (path != string.Empty)
                        {
                            string filePath = Server.MapPath(locationDocument.Path);
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                        locationDocument.LocationId = int.Parse(ddlLocation.SelectedValue);
                        locationDocument.Name_CN = txtNameCN.Text;
                        locationDocument.Name_EN = txtNameEN.Text;
                        locationDocument.CreateBy = CurrentUserId;
                        locationDocument.LastModifyTime = DateTime.Now;
                        if (path != string.Empty)
                            locationDocument.Path = path;
                        LocationDocumentPresent.Update(locationDocument);
                    }
                    break;
                case Utility.PageStatus.New:
                    if (!uploadDocument("new", Id, out path))
                        return;
                    Model.LocationDocument newlocationDocument = new Model.LocationDocument()
                    {
                        LocationId = int.Parse(ddlLocation.SelectedValue),
                        Name_CN = txtNameCN.Text,
                        Name_EN = txtNameEN.Text,
                        CreateBy = CurrentUserId,
                        LastModifyTime = DateTime.Now,
                        Path = path,
                    };
                    LocationDocumentPresent.Create(newlocationDocument);
                    break;
            }
            Response.Redirect("/LocationDocument/View.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/LocationDocument/View.aspx");
        }

        protected bool uploadDocument(string status, int productid, out string path)
        {
            lblUploadError.Text = string.Empty;
            path = string.Empty;
            try
            {
                if (!string.IsNullOrWhiteSpace(DocumentFileUpload.FileName))
                {

                    string filename = DocumentFileUpload.FileName;
                    string fileExt = System.IO.Path.GetExtension(DocumentFileUpload.FileName).ToLower();
                    int fileSize = DocumentFileUpload.PostedFile.ContentLength;
                    if (fileSize>10485760)
                    {
                        lblUploadError.Text = "大小超过10M";
                        return false;
                    }
                    if (fileExt != ".ppt" && fileExt != ".pptx" && fileExt != ".doc" && fileExt != ".docx" && fileExt != ".xls" && fileExt != ".xlsx")
                    {
                        lblUploadError.Text = "只能上传PPT,Word,Excel三种文档";
                        return false;
                    }
                    string documentname = DateTime.Now.ToString("yyMMddHHmmss") + "-" + filename;
                    string mapPath = Server.MapPath("\\UploadFolder");
                    string webFilePath = Path.Combine(mapPath, documentname);
                    if (!Directory.Exists(mapPath))
                    {
                        Directory.CreateDirectory(mapPath);
                    }
                    int random = 0;
                    while (true)
                    {
                        if (File.Exists(webFilePath))
                        {
                            random++;
                            documentname = System.IO.Path.GetFileNameWithoutExtension(documentname) + "(" + random + ")" + System.IO.Path.GetExtension(documentname);
                            webFilePath = Path.Combine(mapPath, documentname);
                        }
                        else
                        {
                            DocumentFileUpload.SaveAs(webFilePath);
                            path = "\\UploadFolder\\" + documentname;
                            break;
                        }
                    }                            
                }
                else 
                {
                    if (status.Equals("new"))
                    {
                        lblUploadError.Text = "请选择一个文档";
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                lblUploadError.Text = ex.Message;
                return false;
            }

            return true;
        }
    }
}